﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace AIC_CD
{
    public partial class DanhMucMau8 : System.Web.UI.Page
    {
        private static int sID;
        private string MyAction = MyConst.Action.Addnew;
        private bool Change = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermision();
            formUpdate.Visible = false;


            lblFormName.InnerText = "Quản trị nội dung Mẫu báo cáo số 8";
            if (!IsPostBack)
            {
                BindDataToGrid("");
            }

        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("Index.aspx");
        }


        protected void grdDanhMuc_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            sID = Convert.ToInt32(e.CommandArgument);
            DataTable DanhMucTable = GetChiTietDanhMuc(sID);
            string sql = "";
            if (e.CommandName == MyConst.Action.Update)
            {
                formUpdate.Visible = true;
                lblSTT.Text = DanhMucTable.Rows[0]["STT"].ToString();
                txtTenDanhMuc.Value = DanhMucTable.Rows[0][2].ToString();
                chkDeMuc.Checked = DanhMucTable.Rows[0]["IdDeMuc"].ToString().Equals("0") ? false : true;
                btnLuu.CommandName = MyConst.Action.Update;
            }
            else if (e.CommandName == MyConst.Action.Delete)
            {
                if (DanhMucTable.Rows[0]["IdDeMuc"].ToString().Equals("1"))
                {
                    MyCommon.AddMessage(this.Master, "Không thể xóa đề mục báo cáo", MyConst.MessageType.Warning);
                }
                else
                {
                    string STT = DanhMucTable.Rows[0]["STT"].ToString();
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE dbo.tblDanhMucMau8 SET STT = STT - 1 WHERE STT IS NOT NULL AND STT > " + STT);
                    sql = "DELETE FROM dbo.tblDanhMucMau8 WHERE ID = @ID";
                    List<SqlParameter> lstParameter = new List<SqlParameter>();
                    lstParameter.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, sID));
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sql, lstParameter);
                    BindDataToGrid("");
                }
            }
        }

        protected void btnThem_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = true;
            chkDeMuc.Checked = false;
            txtTenDanhMuc.Value = "";
            btnLuu.CommandName = MyConst.Action.Addnew;
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            SqlTransaction trans = SqlHelper.BeginTransaction();
            try
            {
                int UserID = Convert.ToInt32(Session["userid"]);
                if (btnLuu.CommandName == MyConst.Action.Addnew)
                {
                    InsertDanhMuc(txtTenDanhMuc.Value, UserID);
                    BindDataToGrid("");
                    MyCommon.AddMessage(this.Page.Master, "Thêm mới thành công !", MyConst.MessageType.Success);
                }
                else if (btnLuu.CommandName == MyConst.Action.Update)
                {
                    UpdateDanhMuc(sID, txtTenDanhMuc.Value, UserID);
                    BindDataToGrid("");
                    MyCommon.AddMessage(this.Page.Master, "Cập nhật thành công !", MyConst.MessageType.Success);
                }
                trans.Commit();
            }
            catch (Exception)
            {
                trans.Rollback();
                MyCommon.AddMessage(this.Page.Master, "Lỗi hệ thống !", MyConst.MessageType.Error);
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
            formUpdate.Visible = false;
        }

        #region Ham chuc nang

        protected void BindDataToGrid(string TenDanhMuc)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@TenDM", SqlDbType.NVarChar, ParameterDirection.Input, TenDanhMuc));
            string sql = "SELECT DM.ID ,DM.STT ,DM.TenDM , " +
                         "CONVERT(NVARCHAR(10),DM.CreateDate,103)+' '+ CONVERT(NVARCHAR(10),DM.CreateDate,108) CreateDate, " +
                         "CONVERT(NVARCHAR(10),DM.UpdateDate ,103)+' '+ CONVERT(NVARCHAR(10),DM.UpdateDate ,108) UpdateDate, " +
                         "U.HoTen " +
                         "FROM dbo.tblDanhMucMau8 DM " +
                         "LEFT JOIN dbo.tblUser U ON U.id = DM.UserID " +
                         "WHERE (DM.TenDM like N'%'+@TenDM+'%' OR @TenDM = '')";
            grdDanhMuc.DataSource = SqlHelper.ExecuteDataTable(CommandType.Text, sql, arrParams);
            grdDanhMuc.DataBind();
        }

        protected DataTable GetChiTietDanhMuc(int ID)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@ID", SqlDbType.Int, ParameterDirection.Input, ID));
            return SqlHelper.ExecuteDataTable(CommandType.Text, "Select * from tblDanhMucMau8 where ID = @ID", arrParams);
        }

        protected void InsertDanhMuc(string TenDanhMuc, int UserID)
        {
            int STT;
            string sql = "";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@TenDanhMuc", SqlDbType.NVarChar, ParameterDirection.Input, TenDanhMuc));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
            if (!chkDeMuc.Checked)
            {
                STT = Convert.ToInt32(SqlHelper.ExecuteScalar(CommandType.Text, "SELECT MAX(ISNULL(STT,0)) FROM dbo.tblDanhMucMau8")) + 1;
                sql = "INSERT  INTO dbo.tblDanhMucMau8(" +
                         "STT,TenDM,IdDeMuc,CreateDate,UpdateDate,UserID)" +
                         "VALUES  (" + STT + ",@TenDanhMuc,0,GETDATE(),GETDATE(),@UserID)";
            }
            else
            {
                sql = "INSERT  INTO dbo.tblDanhMucMau8(" +
                         "TenDM,IdDeMuc,CreateDate,UpdateDate,UserID)" +
                         "VALUES  (@MaDanhMuc,@TenDanhMuc,1,GETDATE(),GETDATE(),@UserID)";
            }

            SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected void UpdateDanhMuc(int IDDanhMuc, string TenDanhMuc, int UserID)
        {
            if (Change)
            {

                if (chkDeMuc.Checked)
                {
                    string STT = SqlHelper.ExecuteScalar(CommandType.Text, "SELECT STT FROM dbo.tblDanhMucMau8 WHERE ID = " + IDDanhMuc).ToString();
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE dbo.tblDanhMucMau8 SET STT = STT - 1 WHERE STT IS NOT NULL AND STT > " + STT);
                    SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE dbo.tblDanhMucMau8 SET STT = NULL,IdDeMuc = 1 WHERE ID = " + IDDanhMuc);
                }
                else
                {
                    string sql = "SELECT MAX(ISNULL(STT,0)) FROM dbo.tblDanhMucMau8 WHERE ID < " + IDDanhMuc;
                    if (SqlHelper.ExecuteScalar(CommandType.Text, sql) != DBNull.Value)
                    {
                        int STT = Convert.ToInt32(SqlHelper.ExecuteScalar(CommandType.Text, sql).ToString()) + 1;
                        SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE dbo.tblDanhMucMau8 SET STT = STT + 1 WHERE STT IS NOT NULL AND ID > " + IDDanhMuc);
                        SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE dbo.tblDanhMucMau8 SET STT = " + STT + ",IdDeMuc = 0 WHERE ID = " + IDDanhMuc);
                    }
                    else
                    {
                        SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE dbo.tblDanhMucMau8 SET STT = STT + 1 WHERE STT IS NOT NULL AND ID > " + IDDanhMuc);
                        SqlHelper.ExecuteNonQuery(CommandType.Text, "UPDATE dbo.tblDanhMucMau8 SET STT = 1,IdDeMuc = 0 WHERE ID = " + IDDanhMuc);
                    }

                }
            }
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@IDDanhMuc", SqlDbType.Int, ParameterDirection.Input, IDDanhMuc));
            arrParams.Add(SqlHelper.CreateParameterObject("@TenDanhMuc", SqlDbType.NVarChar, ParameterDirection.Input, TenDanhMuc));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
            string sSql = "UPDATE dbo.tblDanhMucMau8 SET TenDM=@TenDanhMuc, UpdateDate=GETDATE(),UserID=@UserID WHERE ID = @IDDanhMuc";
            SqlHelper.ExecuteNonQuery(CommandType.Text, sSql, arrParams);

        }

        public void CheckPermision()
        {
            int NhomUser = Convert.ToInt32(Session["quyenuser"]);
            int QuyenUser = MyCommon.GetQuyenID(MyConst.DanhMuc.NoiDungMau8.Ma);
            Dictionary<string, int> Role = MyCommon.CheckPermission(NhomUser, QuyenUser);
            if (Role["Xem"] == 0)
            {
                MyCommon.AddMessage(this.Master, "Bạn không được phân quyền để thực hiện chức năng này", MyConst.MessageType.Warning);
                Response.Redirect("index.aspx");
            }
            else
            {
                if (Role["Them"] == 0)
                {
                    btnThem.Enabled = false;
                }
                if (Role["Sua"] == 0)
                {
                    grdDanhMuc.Columns[grdDanhMuc.Columns.Count - 2].Visible = false;
                }
                if (Role["Xoa"] == 0)
                {
                    grdDanhMuc.Columns[grdDanhMuc.Columns.Count - 1].Visible = false;
                }
            }
        }
        #endregion  Ham chuc nang

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindDataToGrid(txtSearch.Text.Trim());
        }

        protected void chkDeMuc_CheckedChanged(object sender, EventArgs e)
        {
            Change = true;
        }
    }
}
